#--Install / load packages
rm(list = ls())
pacman::p_load(sf, here, tmap, osmdata, tidyverse, data.table, rio, tidyverse, flextable, mapview, units, spdep, deldir, sp, rgeoda, leaflet, viridis, crosstalk, leaflet.extras, plotly)
#--Import street-level crime data
crime <- rio::import(here::here("3_output", "crime_2024-05-09.csv")) |>
dplyr::mutate(category = stringr::str_replace_all(category, "-", " ")) |>
sf::st_as_sf(coords = c("location.longitude", "location.latitude"), crs = 4326, dim = "XY")
#from 2021-04 to 2024-03
#--Import Barnet shapefile
bnt_shp <- sf::st_read(here("1_data", "9_geo", "bnt_lad.json"), crs = 4326, quiet = TRUE) |>
st_make_valid()
#--Filter crime that intersects or is in within Barnet file
#crime_bnt <- crime[which(st_covers(bnt_shp, crime, sparse = FALSE)),]
crime_bnt <- crime[which(st_intersects(bnt_shp, crime, sparse = FALSE)),]
#--Amend date column
crime_bnt$date <- as.Date(paste0(crime_bnt$month, "-01"))
#--Create shared_data
shared_data <- SharedData$new(crime_bnt)
#--Assign colour palette
n_pal <- length(unique(crime_bnt$category))
crime_pal <- leaflet::colorFactor(turbo(n_pal), crime_bnt$category)
#--Create filters
month_slider <- crosstalk::filter_slider("date", "Date", shared_data, ~date, width = "100%")
category_checkbox <- crosstalk::filter_checkbox("category", "Category", shared_data, ~category, columns = 1)
#--Create map
m_eda <- leaflet(data = shared_data) |>
leaflet::addProviderTiles("CartoDB.Positron")|>
leaflet::addCircleMarkers(color = ~crime_pal(category), radius = 2) |>
leaflet::addLegend("bottomright", pal = crime_pal, values = ~category, title = "Category") |>
leaflet::addPolygons(data = bnt_shp, fill = FALSE, color = "black")
#--Pull everything together
crosstalk::bscols(
widths = c(1, 3, 8),
htmltools::div(), #hack to solve the fiters getting clipped
list(month_slider,
category_checkbox),
m_eda
)